<?php

namespace app\model\activity;

use app\base\BaseModel;
use app\model\goods\GoodsCommonModel;
use app\model\goods\GoodsModel;
use app\model\goods\GoodsStoreModel;
use app\model\order\OrderGroupModel;
use app\model\store\StoreModel;
use think\Exception;
use think\model\concern\SoftDelete;

/**
 * 模型-ActivityGoodsModel
 * Class ActivityGoodsModel
 * @package app\model
 */
class ActivityGoodsModel extends BaseModel
{
    use SoftDelete;

    protected $name = 'activity_goods';

    /**
     * 店铺id 查询范围
     * @param $query
     * @param $nav_id
     */
    public function scopeNavId($query, $nav_id)
    {
        if (!empty($nav_id)) {
            $query->where('g.goods_nav_id', $nav_id);
        }
    }

    public function getPageActivityList($map, $mapLike, $order, $current_page, $list_rows, $field = 'a.*,g.goods_title,g.goods_image,g.goods_cost_price,g.goods_market_price,g.goods_sell_price')
    {
        $model = $this;
        $model = $model->alias("a")->leftJoin("t_goods_common g", "a.attribute_ids=g.attribute_ids")->field($field);
        if (!empty($mapLike)) {
            foreach ($mapLike as $key => $value) {
                $model = $model->whereLike($key, $value, "OR");
            }
        }
        foreach ($map as $k => $v) {
            $model = $model->where($k, $v);
        }
        $dataList = $model->order($order)->paginate(['page' => $current_page, 'list_rows' => $list_rows], false);
        $current = $dataList->currentPage();
        $total = $dataList->total();
        $limit = $dataList->listRows();
        $data_temp = $dataList->items();
        $order_group_model = new OrderGroupModel();
        foreach ($data_temp as &$value) {
            $order_group_temp = $order_group_model->getGroup($value['goods_id']);
            $now_condition = 0;
            if (!empty($order_group_temp)) {
                $order_group_temp = array_shift($order_group_temp);
                $now_condition = $order_group_temp['total'];
            }
            $value['now_condition'] = $now_condition;
        }
        $ret = ['total' => $total, 'current' => $current, 'limit' => $limit, 'dataList' => $data_temp];
        return $ret;
    }


    /**
     * 获取活动商品列表
     * @param int $activity_id
     * @param string $nav_id
     * @param int $page
     * @param int $limit
     * @param string $field
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getGoodsList($activity_id = 1, $nav_id = '', $page = 1, $limit = 10, $field = "a.goods_id,a.sell_price,a.activity_id,a.condition,a.goods_storage,c.attribute_names,c.goods_title,c.goods_image,c.goods_market_price,c.goods_sell_price,t.store_id,t.end_time,g.goods_nav_id")
    {
        $goods_list = $this->alias('a')
            ->leftJoin('t_goods g', 'g.id=a.goods_id')
            ->join('t_activity t', 't.id=a.activity_id')
            ->join('t_goods_common c', 'c.attribute_ids=a.attribute_ids')
            ->where('a.activity_id', $activity_id)
            ->navId($nav_id)
            ->field($field)
            ->limit(($page - 1) * $limit, $limit)->select();
        foreach ($goods_list as &$value) {
            $value['store'] = StoreModel::getStoreInfo($value['store_id'], 'id,store_name,store_label');
            $month = intval(date("m", $value['end_time']));
            $day = intval(date("d", $value['end_time']));
            $value['end_time_str'] = $month . "月" . $day . "日";
        }
        return $goods_list;
    }

    /**
     * 获取团购商品
     * @param $goods_id
     * @param $attribute_ids
     * @param $activity_id
     * @param string $field
     * @return array
     */
    public function getGoods($goods_id, $attribute_ids = '', $activity_id = 1, $field = 'a.*,g.freight_id,g.store_id')
    {
        $goods_data = $this->alias("a")
            ->leftJoin("t_goods_common c", "a.goods_id=c.goods_id")
            ->leftJoin("t_goods g", "a.goods_id=g.id")
            ->where('a.goods_id', $goods_id)
            ->where('a.activity_id', $activity_id)
            ->where('c.attribute_ids', $attribute_ids)
            ->field($field)->find();
        if (empty($goods_data)) {
            return [];
        }
        $goods_common_model = new GoodsCommonModel();
        $goods = $goods_common_model->getCommonAttrId($attribute_ids);
        $goods['activity_goods_id'] = $goods_data['id'];
        $goods['activity_id'] = $goods_data['activity_id'];
        $goods['sell_price'] = $goods_data['sell_price'];
        $goods['freight_id'] = $goods_data['freight_id'];
        $goods['store_id'] = $goods_data['store_id'];
        $goods['condition'] = $goods_data['condition'];
        $goods['condition_time'] = $goods_data['condition_time'];
        $goods['goods_storage'] = $goods_data['goods_storage'];
        return $goods;
    }

    /**
     * 商品库存变化
     * @param $storage
     * $storage['target_id']  活动id
     * $storage['goods_id']  商品id
     * $storage['storage']  变化的库存数量
     * $storage['admin_id']  操作管理员id
     * $storage['remark']  备注信息
     * @param string $change 变化方式
     * @param int $user_id
     * @return bool
     * @throws \Exception
     */
    public function changeStore($storage, $change, $user_id = 0)
    {
        $this->startTrans();
        $map = ['activity_id' => $storage['target_id'], 'goods_id' => $storage['goods_id']];
        $goods_data = $this->where($map)->find();
        if (empty($goods_data)) {
            $goods_data['goods_storage'] = 0;
        }
        if ($change == 'add') {
            $up_data = [
                'goods_storage' => $storage['storage'] + intval($goods_data['goods_storage'])
            ];
        } else {
            if ((intval($goods_data['goods_storage']) - $storage['storage']) < 0) {
                $this->rollback();
                return false;
            }
            $up_data = [
                'goods_storage' => intval($goods_data['goods_storage']) - $storage['storage']
            ];
            if (intval($up_data['goods_storage']) == 0) {
                $up_data['delete_time'] = time();
            }
            if (!empty($user_id)) {
                $storage['remark'] = "活动商品售卖";
            }
        }
        $ret = $this->where($map)->update($up_data);
        if ($ret !== false) {
            $in_data = [
                'goods_id' => $storage['goods_id'],
                'last_storage' => intval($goods_data['goods_storage']),
                'storage' => $storage['storage'],
                'change' => $change,
                'user_id' => $user_id,
                'target_id' => $storage['target_id'],
                'operate' => "activity",
                'admin_id' => $storage['admin_id'],
                'remark' => $storage['remark'],
                'add_time' => time()
            ];
            $goods_store_model = new GoodsStoreModel();
            $ret = $goods_store_model->addStorage($in_data);
            if ($ret !== false) {
                $this->commit();
                return true;
            }
        }
        $this->rollback();
        return false;
    }

    /**
     * 添加活动商品
     * @param array $goods
     * $goods['goods_storage'] 变化库存
     * $goods['admin_id'] 管理员id
     * @return bool
     * @throws \Exception
     */
    public function addGoods($goods = [])
    {
        $attribute_ids = $goods['attribute_ids'];
        $sell_price = $goods['sell_price'];
        unset($goods['attribute_ids']);
        unset($goods['sell_price']);
        $ret = false;
        $goods_common_model = new GoodsCommonModel();
        $goods_list = $goods_common_model->getCommonAttrIdIn($attribute_ids);
        foreach ($goods_list as $key => $value) {
            $item = $goods;
            $item['attribute_ids'] = $value['attribute_ids'];
            $item['goods_id'] = $value['goods_id'];
            $item['sell_price'] = floatval($value['goods_sell_price']) * ($sell_price / 100);
            $map = [
                'activity_id' => $item['activity_id'],
                'goods_id' => $item['goods_id'],
                'attribute_ids' => $item['attribute_ids'],
            ];
            $goods_storage = $item['goods_storage'];
            $admin_id = $item['admin_id'];
            unset($item['goods_storage']);
            unset($item['admin_id']);
            $this->withTrashed = true;
            $temp_goods = $this->where($map)->find();
            if (empty($temp_goods)) {
                $ret = $this->saveData($item);
                if ($ret === false) {
                    throw new \think\Exception("商品添加失败", 0);
                } else {
                    $m_ret = true;
                }
            } else {
                $delete_time = $temp_goods['delete_time'];
                if (!empty($delete_time)) {
                    $item['delete_time'] = 0;
                    $ret = $this->where('id', $temp_goods['id'])->update($item);
                    if ($ret === false) {
                        throw new \think\Exception("商品添加失败", 0);
                    } else {
                        $m_ret = true;
                    }
                } else {
                    throw new \think\Exception("商品已存在", 0);
                }
            }
            if ($m_ret) {
                $goods_model = new GoodsModel();
                $storage = [
                    'storage' => $goods_storage,
                    'attribute_ids' => $item['attribute_ids'],
                    'target_id' => $item['activity_id'],
                ];
                $operate = [
                    'operate' => 'activity',
                    'admin_id' => $admin_id
                ];
                $ret = $goods_model->changeStore($item['goods_id'], $storage, 'add', 0, $operate, '添加活动商品');
            }
        }
        return $ret;
    }

    /**
     * 删除活动商品
     * @param $id
     * @param $admin_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delGoods($id, $admin_id)
    {

        $goods_temp = $this->where('id', $id)->find();
        if (empty($goods_temp)) {
            return false;
        }
        $goods_storage = $goods_temp['goods_storage'];
        $goods_id = $goods_temp['goods_id'];
        $activity_id = $goods_temp['activity_id'];
        $goods_model = new GoodsModel();
        $storage = [
            'storage' => $goods_storage,
            'target_id' => $activity_id
        ];
        $operate = [
            'operate' => 'activity',
            'admin_id' => $admin_id
        ];
        $ret = $goods_model->changeStore($goods_id, $storage, 'sub', 0, $operate, '退还活动商品');
        if ($ret === true) {
            $this::destroy(['id' => $id]);
            return true;
        }
        return false;
    }

    /**
     * 判断商品是否是拼团商品
     * @param $goods_id
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function isExist($goods_id)
    {
        $goods_gruop = [];
        $is_group_goods = 0;
        $order_number = 0;
        $sell_price = 0;
        $temp = self::where(['goods_id' => $goods_id])->field('id,sell_price,goods_storage')->find();
        if (!empty($temp)) {
            $order_group_model = new OrderGroupModel();
            $goods_gruop = $order_group_model->getGroup($goods_id);
            if (!empty($goods_gruop)) {
                foreach ($goods_gruop as $value) {
                    $order_number += intval($value['total']);
                }
            }
            $is_group_goods = 1;
            $sell_price = $temp['sell_price'];
            $goods_storage = $temp['goods_storage'];
        }

        $return_data = [
            'order_number' => $order_number,
            'goods_group' => $goods_gruop,
            'is_group_goods' => $is_group_goods,
            'sell_price' => $sell_price,
            'goods_storage' => $goods_storage,
        ];
        return $return_data;
    }
}
